package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @Author: qingtao
 * @Date 2022/3/22 20:03
 */
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {
    @Autowired(required = false)
    private ShoppingCartService shoppingCartService;

    @Autowired(required = false)
    private HttpSession session;

    /**
     * 添加购物车
     * @param shoppingCart
     * @return
     */
    @PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart){
        //1.获得当前等登陆者
        Long userId = (Long)session.getAttribute("user");
        shoppingCart.setUserId(userId);
        //添加成功之后，要把当前的购物项返回
        ShoppingCart add = shoppingCartService.add(shoppingCart);
        return R.success(add);
    }

    /**
     * 减少
     * @param shoppingCart
     * @return
     */
    @PostMapping("/sub")
    public R<ShoppingCart> sub(@RequestBody ShoppingCart shoppingCart){
        Long userId = (Long)session.getAttribute("user");
        shoppingCart.setUserId(userId);
        ShoppingCart sub = shoppingCartService.sub(shoppingCart);
        return R.success(sub);
    }

    /**
     * 显示购物车
     * @return
     */
    @GetMapping("/list")
    public R<List<ShoppingCart>> list(){
        Long userId = (Long)session.getAttribute("user");
        return R.success(shoppingCartService.findCartByUserId(userId));
    }

    /**
     * 清空购物车
     * 根据userId
     * @return
     */
    @DeleteMapping("/clean")
    public R<String> clear(){
        Long userId = (Long)session.getAttribute("user");
        shoppingCartService.clear(userId);
        return R.success("删除成功");
    }
}
